<template>
	<div class="box" :class="isHidden ? 'hidden-pannel' : ''">
		<div class="hidden-btn" @click="isHidden = !isHidden"></div>
		<!-- <div class="type-tab">
			<div
				v-for="i in typeList"
				:key="i.icon"
				class="type-item"
				:class="i.icon == currentType ? 'active' : ''"
				@click="swichtab(i.icon)"
			>
				<img class="w-5" :src="getImageUrl(i.icon, i.icon == currentType ? 'on' : 'off')" alt="" />
				<div>{{ i.name }}</div>
			</div>
			<div class="split-line-A"></div>
			<div class="split-line-B"></div>
		</div> -->
		<!-- 解译组件 -->
		<div v-show="type == 'task'" class="task-list">
			<div
				v-for="item in taskList"
				:key="item.taskId"
				class="task-item"
				:class="activeTask == item.taskId ? 'active' : ''"
				@click="handleOperation(item, operationList[0])"
			>
				<div class="left-top">
					<svg-icon name="type-A"></svg-icon>
					<div class="name w-full truncate">
						<el-tooltip
							effect="dark"
							:content="translateInterpreType(item.interpretType)"
							placement="top"
							:show-after="500"
						>
							{{ item.taskName || getFileName(item.preFilePath) }}
						</el-tooltip>
					</div>
				</div>
				<div class="right-top">{{ item.createTime }}</div>
				<div class="left-bottom">
					<el-progress
						:percentage="item.taskProgress"
						:stroke-width="10"
						:show-text="false"
						:status="item.taskStatus === -1 ? 'exception' : ''"
					></el-progress>
				</div>
				<div class="right-bottom">
					<svg-icon
						v-for="oper in operationList"
						:key="oper.type"
						:name="
							activeTask === item.taskId && activeOption === oper.type
								? oper.iconActive
								: oper.iconNormal
						"
						:tip="oper.tip"
						@click.stop="handleOperation(item, oper)"
					/>
				</div>
			</div>
		</div>
		<!-- 数据组件 -->
		<div v-show="type == 'data'" class="data-list">
			<div>
				<div style="margin-left: 20px; display: flex">
					<el-input v-model="search" size="default" style="width: 180px" placeholder="请输入" />
					<el-button class="elBtn search-btn" style="margin-left: 10px" @click="dealSearch">
						<img src="@img/main/search-light.png" />
						查询
					</el-button>
					<el-button class="elBtn reset-btn" style="width: 50px" @click="resetSearch">
						重置
					</el-button>
				</div>
				<ul>
					<li v-for="(item, index) in ftpList" :key="index">
						<tree-items
							:layer-children="item.children"
							:level="1"
							@view="showTiff"
							@process="openAipopup"
							@download="downloadftp"
							@outpicture="outpic"
							@checkChange="checkChange"
							@clickItem="clickItem"
						></tree-items>
					</li>
				</ul>
			</div>
		</div>
		<el-dialog v-model="dialogVisible" title="下载影像" width="300px" append-to-body>
			<div>
				{{ pickftp }}
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button type="primary" @click="handleAdd">确定</el-button>
					<el-button @click="handleClose">取消</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-model="resultDialog" title="分析结果" width="850px" append-to-body>
			<vectorAnalysis :chartsData="chartsData" :listData="[]" />
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { getTaskList, delTask } from "@/api/ai-processing";
import { getUserFileList, getUserFileDetail, getqueryDirs } from "@/api/data-management/index";
import type { taskListItem, dataListItem, Tree } from "@/api/ai-processing/types";
import { useTaskStore, useUserStore } from "@/store";
import mapTool from "@/utils/maptools/map";
import { translateInterpreType, getFileName, handleTreeData } from "@/utils/tsTools";
import { ElMessage, ElMessageBox } from "element-plus";
import { download } from "@/utils/request";
import vectorAnalysis from "./vectorAnalysis.vue";
import { getvectorAnalysis } from "@/api/data-management/index";
import { usePermissionCheck } from "@/utils/hooks/useRole";
import { clearToken } from "@/utils/auth";
import Log from "../system/log.vue";

const userStore = useUserStore();
const dialogVisible = ref(false);
const resultDialog = ref(false);
const chartsData = ref([]);
const getUserCode = computed(() => userStore.userCode);
const props = defineProps({
	isEdit: {
		type: Boolean,
	},
	type: {
		type: String,
	},
});
const swichtab = (type: string) => {
	currentType.value = type;
	mapTool.clearVectorLayer("ai-interpretation");
	mapTool.removeAllSlicingLayer("ai-interpretation");
	activeOption.value = "";
	taskStore.setInfo({
		vecLegendShow: false,
	});
	emits("tiflegendshow", false);
};
const emits = defineEmits(["watchShp", "editShp", "exitEdit", "tiflegendshow"]);
const pickftp = computed(() => taskStore.viewftp.filePath);
const downloadFTPpick = ref("");
const dowloadType = ref("" as string);
// 解译、数据 tab切换
const currentType = ref("task");
const typeList = [
	{
		icon: "task",
		name: "解译",
	},
	{
		icon: "data",
		name: "数据",
	},
];
const getImageUrl = (iconName: string, status: string) => {
	return new URL(`../../../assets/images/main/${iconName}-${status}@2x.png`, import.meta.url).href;
};
const dealSearch = async () => {
	searchByKey(search.value);
};
const searchByKey = async (key: string) => {
	let { data: fileList } = await getUserFileList(getUserCode.value, true, key);
	ftpList.value[0] = handleTreeData(fileList);
	// if (permissionTool.checkPermission()) {
	// 	// 管理员移除掉 我的数据
	// 	ftpList.value[0].children.pop();
	// }
};
const resetSearch = () => {
	search.value = "";
	searchByKey("");
};
// 切换显隐
const isHidden = ref(false);
/**------------------------解译任务相关------------------------------*/
// #region 解译组件

const taskList: Ref<taskListItem[]> = ref([]);
// 这里的逻辑是 维护一个是否结束状态，如果结束就不再请求，如果没有结束就轮询，结束条件是请求中列表所有任务的taskProgress为100
const isEnd = ref(false);
const router = useRouter();
const getLeftList = async () => {
	let res = await getTaskList(2);
	if (res.code === 401) {
		clearToken();
		// router.push("/login");
	}
	// console.log("左侧任务当前列表", res);
	taskList.value = res.rows;
	for (const iterator of taskList.value) {
		if (iterator.taskProgress !== 100 && iterator.taskStatus !== -1) {
			isEnd.value = false;
			break;
		} else {
			isEnd.value = true;
		}
	}
	if (!isEnd.value) {
		setTimeout(() => {
			polling();
		}, 5000);
	}
};
// 轮询
const polling = () => {
	if (isEnd.value) {
		return;
	}
	// console.log("轮询中");
	getLeftList();
};
onMounted(async () => {
	console.log("@22222");

	getLeftList();
});
const search = ref("");
// 激活任务
const activeTask = ref(0);
// 矢量相关操作列表
const operationList = [
	{
		type: "watch",
		iconNormal: "task_watch_nor",
		iconActive: "task_watch_act",
		label: "",
		tip: "查看",
	},
	{
		type: "edit",
		iconNormal: "task_edit_nor",
		iconActive: "task_edit_act",
		label: "",
		tip: "编辑",
	},
	{
		type: "shp",
		iconNormal: "task_shp_nor",
		iconActive: "task_shp_act",
		label: "",
		tip: "下载shp",
	},
	{
		type: "area",
		iconNormal: "task_area_nor",
		iconActive: "task_png_act",
		label: "",
		tip: "面积统计",
	},
	{
		type: "del",
		iconNormal: "task_del_nor",
		iconActive: "task_del_act",
		label: "",
		tip: "删除任务",
	},
];
// 激活操作项
const activeOption = ref("");
// 操作事件
const handleOperation = async (item: taskListItem, oper: any) => {
	if (oper.type === "edit" && item.taskProgress !== 100) {
		ElMessage.info("任务未完成，请稍后编辑");
		return;
	}
	if (activeOption.value === "edit") {
		try {
			await ElMessageBox.confirm(
				"当前正在编辑任务，请确保编辑内容以保存，是否放弃编辑进行其他操作?",
				"提示",
				{
					confirmButtonText: "确认",
					cancelButtonText: "取消",
				}
			);
			emits("exitEdit");
			await nextTick();
			activeOption.value = oper.type;
		} catch (e) {
			return;
		}
	}
	switch (oper.type) {
		// 查看矢量
		case "watch": {
			taskStore.setInfo({
				currentInterpretType: item.interpretType,
			});
			if (item.taskStatus === -1) {
				ElMessage({
					message: "任务已失败",
					type: "error",
				});
				return;
			}
			console.log("展示矢量", activeTask.value, item.taskId);
			console.log("展示矢量", activeOption.value, oper.type);

			if (activeTask.value === item.taskId && activeOption.value === oper.type) {
				activeOption.value = "";
				emits("watchShp", item, false);
			} else {
				activeTask.value = item.taskId;
				activeOption.value = oper.type;
				emits("watchShp", item, true);
			}
			break;
		}
		// 编辑矢量
		case "edit": {
			if (activeTask.value === item.taskId && activeOption.value === oper.type) {
				activeOption.value = "";
				emits("editShp", item, false);
			} else {
				activeTask.value = item.taskId;
				activeOption.value = oper.type;
				emits("editShp", item, true);
			}
			break;
		}
		// 导出shp
		case "shp": {
			download({
				url: `/task/geo/exportShp?taskId=${item.taskId}`,
			});
			break;
		}
		// 导出图片
		case "area": {
			// download({
			// 	url: `/task/geo/exportImg?taskId=${item.taskId}`,
			// });
			console.log(item.taskId);
			// debugger;
			let res = await getvectorAnalysis(item.taskId.toString());
			chartsData.value = res.data;
			resultDialog.value = true;

			// 	taskStore.setInfo({
			// 	vecPopshow: true,
			// });
			break;
		}
		// 删除任务
		case "del": {
			activeTask.value = item.taskId;
			activeOption.value = oper.type;
			await nextTick(() => {
				ElMessageBox.confirm("确认删除该任务吗?", "提示", {
					confirmButtonText: "确认",
					cancelButtonText: "取消",
				})
					.then((g) => {
						delTask(item.taskId)
							.then((data) => {
								ElMessage({
									message: data.msg,
									type: "success",
									duration: 5 * 1000,
								});
							})
							.then(() => {
								getLeftList();
							});
					})
					.catch((err) => {
						activeOption.value = "";
					});
			});
			break;
		}
	}
};

// 右侧解译弹窗相关
const taskStore = useTaskStore();
// 通过监听store的taskStatus来更新左侧列表
watch(
	() => taskStore.taskStatus,
	() => {
		getLeftList();
	}
);
const openAipopup = async (info: dataListItem) => {
	let res = await showTiff(info, true);
	if (info.type == "1") {
		taskStore.setInfo({
			vecLegendShow: false,
			taskStatus: true,
			shpPopshow: false,
			taskInfo: {
				...info,
				geo: res.data.geo,
			},
		});
	} else {
		taskStore.setInfo({
			shpPopshow: false,
		});
		taskStore.setInfo({
			vecLegendShow: true,
			shpPopshow: true,
			taskStatus: false,
			taskInfo: {
				...info,
				geo: res.data.geo,
			},
		});
	}
};
const downloading = ref(false);
const handleAdd = () => {
	downloading.value = true;
	let filePath = downloadFTPpick.value;
	let baseURL = BASE_CONFIG["baseURL"];
	console.log(filePath, "filePath");

	window.location.href = baseURL + "/common/download/ftp?" + "filePath=" + encodeFilePath(filePath);
	handleClose();
	// download({
	// 	url: "/common/download/ftp",
	// 	params: {
	// 		filePath,
	// 	},
	// }).then((res) => {
	// 	ElMessage.success("下载成功");
	// 	downloading.value = false;
	// 	handleClose();
	// });
};
const encodeFilePath = (filePath: any) => {
	const normalizedPath = filePath.replace(/\\/g, "\\\\");
	return encodeURIComponent(normalizedPath);
};
const handleClose = () => {
	dialogVisible.value = false;
	downloading.value = false;
};
const updateChildrenRecursively = (list: any, targetId: any, childrenData: any) => {
	console.log(list, targetId, childrenData, "更新子节点");
	for (let item of list) {
		if (item.id === targetId) {
			item.children = childrenData;
			return list;
		}
		if (item.children && item.children.length > 0) {
			// 递归处理子节点
			// console.log(item.children, targetId, childrenData, "递归处理子节点");
			updateChildrenRecursively(item.children, targetId, childrenData);
		}
	}
};
const findPathById = (list: any, targetId: any, path = []) => {
	for (let item of list) {
		if (item.id === targetId) {
			return [...path, item.name]; // 找到目标节点，返回拼接的路径
		}
		if (item.children && item.children.length > 0) {
			// 递归查找子节点
			const result = findPathById(item.children, targetId, [...path, item.name]);
			if (result.length > 0) {
				return result; // 如果找到路径，返回
			}
		}
	}
	return []; // 如果没有找到，返回空数组
};
const addfiles = (list: any, targetId: any, childrenData: any) => {
	console.log(list, targetId, childrenData, "点击");

	for (let item of list) {
		if (item.id === targetId) {
			item.files = childrenData;
			return list;
		}
		if (item.children && item.children.length > 0) {
			// 递归处理子节点
			// console.log(item.children, targetId, childrenData, "递归处理子节点");
			addfiles(item.children, targetId, childrenData);
		}
	}
};
const clickItem = async (data: Tree) => {
	console.log(data.id, data.name, "查找的属性");

	const path = findPathById(ftpList.value, data.id);
	let name = path.join("\\");
	let res = await getqueryDirs(name);
	if (!res.data) return;
	if (res.data.children.length > 0) {
		updateChildrenRecursively(ftpList.value, data.id, res.data.children);
	} else {
		addfiles(ftpList.value, data.id, res.data.files);
	}

	console.log(res.data.files);
};
const outpic = (info: dataListItem) => {
	console.log("出图", info);
	let url = "";
	if (info.type == "1") {
		url = "/common/download/tifExport";
	} else {
		url = "/common/download/shpExport";
	}
	let id = info.id;
	download({
		url: url,
		params: {
			id,
		},
	}).then((res) => {
		ElMessage.success("下载成功");
		downloading.value = false;
		handleClose();
	});
};
const downloadftp = (info: dataListItem) => {
	taskStore.setInfo({
		viewftp: info,
	});
	dialogVisible.value = true;
	// dowloadType.value = info.type;
	console.log(info, "wwfw");

	if (info.type == "1") {
		downloadFTPpick.value = info.filePath;
	} else {
		downloadFTPpick.value = info.zipFilePath;
	}
	// let filePath = info.filePath;
	// download({
	// 	url: "/common/download/ftp",
	// 	params: {
	// 		filePath,
	// 	},
	// });
};
watch(
	() => props.isEdit,
	() => {
		if (!props.isEdit) {
			activeOption.value = "";
		}
	}
);

// #endregion
/**------------------------解译任务相关------------------------------*/

/**------------------------影像数据相关------------------------------*/
const permissionTool = usePermissionCheck();
// #region 数据组件
const ftpList: Ref<Tree[]> = ref([]);
onMounted(async () => {
	if (typeof getUserCode.value === "undefined") {
		ElMessage({
			message: "请先登录",
			type: "error",
		});
		return;
	}
	let { data: fileList } = await getqueryDirs("");
	// let { data: fileList } = await getUserFileList(getUserCode.value, true, search.value);
	ftpList.value[0] = fileList;
	if (permissionTool.checkPermission()) {
		// 管理员移除掉 我的数据
		ftpList.value[0].children.pop();
	}
	console.log("左侧文件列表：", fileList);
});
/**------------------------影像数据相关------------------------------*/

// #endregion

/* 地图业务相关 */
// 加载tiff影像
const checkChange = async (item: dataListItem) => {
	let res = await getUserFileDetail(item.id);
	console.log(item.checked);
	if (mapTool.hasSlicingLayer("ai-interpretation", res.data.filePath)) {
		if (item.checked) {
			mapTool.locationByWkt("ai-interpretation", res.data.geo);
		} else {
			if (item.type == "1") {
				mapTool.removeSlicingLayer("ai-interpretation", res.data.filePath);
			}
			{
				console.log(res.data, "添加");

				mapTool.removeSlicingLayer("ai-interpretation", res.data.tableName);
			}
		}
	} else {
		if (item.checked) {
			if (item.type == "1") {
				mapTool.locationByWkt("ai-interpretation", res.data.geo);
				mapTool.addSlicingLayer("ai-interpretation", res.data.filePath);
			} else {
				taskStore.setInfo({
					vecLegendShow: true,
				});
				mapTool.locationByBbox("ai-interpretation", res.data.bbox);
				mapTool.addSlicingWFSLayer("ai-interpretation", res.data.shpServiceUrl, res.data.tableName);
				// mapTool.addSlicingLayer("ai-interpretation", res.data.filePath);
			}
		} else {
			mapTool.removeSlicingLayer("ai-interpretation", res.data.tableName);
		}
	}
};
const showTiff = async (item: dataListItem, forceShow = false) => {
	// todo 这里可以加上判断，如果已经在area里面了，就不进行locationByWkt定位
	console.log(item);
	taskStore.setInfo({
		viewftp: item,
		vecLegendShow: item.type == 1 ? false : true,
	});

	let res = await getUserFileDetail(item.id);
	if (mapTool.hasSlicingLayer("ai-interpretation", res.data.filePath)) {
		// mapTool.clearVectorLayer("ai-interpretation");
		mapTool.locationByWkt("ai-interpretation", res.data.geo);
		// if (!forceShow) {
		// 	mapTool.removeAllSlicingLayer("ai-interpretation");
		// }
	} else {
		// mapTool.clearVectorLayer("ai-interpretation");
		// mapTool.removeAllSlicingLayer("ai-interpretation");
		if (item.type == "1") {
			mapTool.locationByWkt("ai-interpretation", res.data.geo);
			mapTool.addSlicingLayer("ai-interpretation", res.data.filePath);
		} else {
			mapTool.locationByBbox("ai-interpretation", res.data.bbox);
			mapTool.addSlicingWFSLayer("ai-interpretation", res.data.shpServiceUrl, res.data.tableName);
			// mapTool.addSlicingLayer("ai-interpretation", res.data.filePath);
		}
	}
	return res;
};
</script>

<style lang="scss" scoped>
@import "@/index.scss";
// 滚动条样式
::-webkit-scrollbar {
	width: 4px;
}

/* 滚动槽 */
::-webkit-scrollbar-track {
	background: transparent;
	border-radius: 18px;
}

/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
	background: #485b73;
	border-radius: 18px;
}

::-webkit-scrollbar-thumb:window-inactive {
	background: #485b73;
	border-radius: 18px;
}

.box {
	@apply absolute z-20;
	width: 334px;
	// height: 75vh;
	height: calc(100% - 4.5rem);
	top: 4rem;
	left: 70px;
	background: linear-gradient(180deg, rgba(1, 12, 18, 0.9) 0%, rgba(4, 36, 70, 0.9) 100%);
	border-radius: 4px;
	opacity: 1;
	border: 1px solid #76c6ff;
	transition: all 0.5s;
	&::before {
		content: "";
		position: absolute;
		top: 3px;
		left: 3px;
		width: 328px;
		height: 7px;
		background: linear-gradient(
			180deg,
			rgba(42, 122, 207, 0.6391) 0%,
			rgba(1, 12, 18, 0.5698) 100%
		);
		border-radius: 6px;
	}
	.hidden-btn {
		@apply absolute bottom-0 left-full top-0 m-auto cursor-pointer;
		width: 21px;
		height: 97px;
		background-image: url("@img/main/hidden-on.png");
	}
	&.hidden-pannel {
		transform: translateX(-332px);
	}
	&.hidden-pannel .hidden-btn {
		background-image: url("@img/main/hidden-off.png");
	}
}
.type-tab {
	@apply relative h-12 w-full;
	@apply flex items-center justify-around;
	@apply text-xl;
	.type-item {
		@apply relative z-10 cursor-pointer;
		@apply flex items-center justify-center;
		> img:first-child {
			@apply mr-2;
		}
		@include art-font(18px, #9ca3a7);
		.active-title {
			@apply absolute;
			top: 34px;
		}
		::before {
			content: "";
			position: absolute;
			top: -10px;
			left: -40px;
			bottom: -10px;
			right: -40px;
		}
	}
	.active {
		color: #fff;
		&::before {
			@apply absolute z-20;
			content: "";
			top: 32px;
			width: 144px;
			height: 6px;
			background-image: url("@img/main/active-title.png");
		}
	}
	.split-line-A {
		@apply absolute bottom-0 left-0 right-0 top-0 z-10 m-auto;
		width: 1px;
		height: 20px;
		background-color: rgba(162, 228, 255, 0.3);
	}
	.split-line-B {
		@apply absolute bottom-0 left-0 right-0 z-10 m-auto;
		width: 320px;
		height: 1px;
		background-color: rgba(162, 228, 255, 0.3);
	}
}
/* 解译组件 */
.task-list {
	@apply px-3;
	height: calc(100% - 2rem);
	overflow-x: hidden;
	overflow-y: auto;
	padding-top: 2px;
}
.task-item {
	@apply box-border cursor-pointer;
	width: 306px;
	height: 76px;
	margin-top: 10px;
	background: rgba(171, 189, 209, 0.12);
	border: 1px solid transparent;
	border-radius: 4px;
	color: #fff;
	display: grid;
	grid-template-columns: 160px 1fr;
	grid-template-rows: 18px 12px;
	grid-gap: 18px 0px;
	padding: 12px 0px;
	.left-top {
		@apply flex items-center;
		> svg {
			@apply mr-3;
		}
		margin-left: 10px;
	}
	.right-top {
		@apply flex items-center justify-center;
		font-size: 14px;
		color: rgba(255, 255, 255, 0.5);
	}
	.left-bottom {
		@apply flex items-center;
		> div {
			@apply w-28;
		}
		margin-left: 10px;
	}
	.right-bottom {
		@apply flex items-center justify-between px-1;
		> svg {
			@apply cursor-pointer;
		}
	}
	&.active {
		background: rgba(7, 151, 255, 0.2);
		border: 1px solid #0095ff;
	}
}

/* 数据组件 */
.data-list {
	--el-fill-color-light: rgba(7, 151, 255, 0.2);
	height: calc(100% - 5rem);
	overflow: auto;
	@apply px-2 py-2 pr-0;
	> div {
		height: calc(37.5vh - 48px);
	}
	:deep(.el-tree) {
		background: transparent;
		color: #fff;
		.el-icon,
		.el-tree-node__expand-icon {
			display: none;
		}
		.el-tree-node__content {
			height: 32px;
			margin: 2px 0;
		}
	}
	.custom-tree-node {
		> div:first-child {
			@apply relative flex w-full pl-3;
			> div {
				@apply flex items-center;
				> img {
					@apply mr-2;
				}
			}
		}
	}
	.data-items {
		@apply pt-3;
		.data-item {
			@apply relative w-full;
			> div {
				@apply flex items-center;
				img {
					@apply mr-3;
					width: 14px;
					height: 14px;
				}
				span {
					@apply truncate;
					width: 200px;
				}
			}
			> span {
				@apply absolute bottom-0 top-0 m-auto flex cursor-pointer items-center;
				right: 14px;
				> img {
					@apply mr-2;
				}
			}
		}
	}
}
.data-list::-webkit-scrollbar {
	width: 8px;
}
</style>
